package com.idealighter.game.roomcard.struct;

import com.idealighter.game.core.annotation.GameCfg;
import com.idealighter.game.core.common.Game;
import com.idealighter.game.core.common.GameMap;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.io.ResolverUtil.AnnotatedWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RoomCardGameCfgMap {
  private static final Logger LOG = LoggerFactory.getLogger(RoomCardGameCfgMap.class);
  private static final String CFG_PATH = "com.idealighter.game.roomcard.struct.gamecfg";
  private static Map<Integer, Class<? extends RoomCardGameCfg<? extends RoomCardGameCfgValue>>> map;

  static {
    map = new HashMap<Integer, Class<? extends RoomCardGameCfg<? extends RoomCardGameCfgValue>>>();

    ResolverUtil<RoomCardGameCfg<? extends RoomCardGameCfgValue>> resolver =
        new ResolverUtil<RoomCardGameCfg<? extends RoomCardGameCfgValue>>().find((type) -> {
          // 首先判断type为RoomCardGameCfg的子类
          if (RoomCardGameCfg.class.isAssignableFrom(type)) {
            // 再判断注解
            return new AnnotatedWith(GameCfg.class).matches(type);
          } else {
            return false;
          }
        }, CFG_PATH);

    // ResolverUtil<RoomCardGameCfg<? extends RoomCardGameCfgValue>> resolver =
    // new ResolverUtil<RoomCardGameCfg<? extends RoomCardGameCfgValue>>()
    // .find(new AnnotatedWith(GameCfg.class), CFG_PATH);

    Set<Class<? extends RoomCardGameCfg<? extends RoomCardGameCfgValue>>> classes =
        resolver.getClasses();
    if (classes != null && !classes.isEmpty()) {
      for (Class<? extends RoomCardGameCfg<? extends RoomCardGameCfgValue>> clz : classes) {
        GameCfg ctl = clz.getAnnotation(GameCfg.class);
        int gameId = ctl.value();
        Game game = GameMap.getGameByGameId(gameId);
        if (game == null) {
          LOG.warn("游戏[{}]cfg配置有误", gameId);
          System.exit(1);
        }
        if (map.containsKey(gameId)) {
          LOG.warn("游戏[{}]cfg重复", gameId);
          System.exit(1);
        }
        map.put(gameId, clz);
      }
    }
  }

  public static Class<? extends RoomCardGameCfg<? extends RoomCardGameCfgValue>> getGameCfgByGameId(
      int gameId) {
    return map.get(gameId);
  }
}
